// packageA/mycomponent/goodsComponent/priceTitleRepertorySales/priceTitleRepertorySales.js
import {formatTimeTwo} from "../../../../../utils/util";
var app = getApp();

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    plugin: {
      type: Object,
    },
    isRent: {
      type: null,
    },
    favorite: {
      type: null,
    },
    activityid: {
      type: null,
    },
    prop_goods_info: {
      type: null,
    },
    isBuy: {
      type: null,
    },
    isBegTime: {
      type: null,
    },
    goodsType: {
      type: null,
    },
    // enterAt提示选择入住时间
    enterAt: {
      type: null,
    },
    gooddatas: {
      type: null,
    },
    fromStock:{
      type: null,
    },
    options:{
      type: null
    }
  },
  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show: function () {
      //72554
      if (this.data.goodsType == "hotelGoods") {
        this.hotelGetData(this.data.prop_goods_info);
      }
    },
  },
  observers: {
    "prop_goods_info,goodsType": function (info, type) {
      if (type == "hotelGoods") {
        this.hotelGetData(info);
      }
    },
    'gooddatas,goodsType,plugin': function (data, type, object) {
      if (data) {
        if(JSON.parse(wx.getStorageSync('mailLanguage')).goods){
          let mailLanguage = JSON.parse(wx.getStorageSync('mailLanguage')).goods;
          this.setData({
            goods_profit:mailLanguage.goods_profit ? mailLanguage.goods_profit : '利润',
            vip_price_name: mailLanguage.vip_price ? mailLanguage.vip_price : '会员价',
            mailLanguage:JSON.parse(wx.getStorageSync('mailLanguage'))
          })
        }
        //* 限时购，宣传语显示
        let goodsInfo = data.get_goods;
        if (goodsInfo) {
          goodsInfo['with_slogan'] = Boolean(goodsInfo.has_one_goods_advertising && goodsInfo.has_one_goods_advertising.is_open == 1);
          if (goodsInfo['with_slogan']) {
            data.get_goods['slogan'] = goodsInfo.has_one_goods_advertising.copywriting;
          }

          if (goodsInfo.member_discount && goodsInfo.member_discount.discount) {
            if (app._isTextEmpty(goodsInfo.member_discount.discount)) {
              this.setData({
                openVip: 1,
              });
            } else {
              this.setData({
                openVip: goodsInfo.member_discount.discount,
              });
            }
            if(goodsInfo.member_discount.all_level_price) this.getMemLevelInfo(goodsInfo);
          }

          if (goodsInfo.available_coupon) {
            this.setData({
              available_coupon: goodsInfo.available_coupon || [],
            });
          }

        }

        if (type != 'hotelGoods' && type != 'group_goods' && type != 'grabGroup' && type != 'retailGood'&& type != 'ywmGroup') {
          this.init(this.data.gooddatas);
        }
        if (type == 'retailGood') {
          this.setData({
            goodsInfo: data
          });
        } else {
          if (type != 'grabGroup') {
            let otherGet = ['group_goods', 'groupwork','ywmGroup'];
            this.setData({
              goodsInfo: otherGet.includes(type) ? data.goods_info : data.get_goods
            });
          }
        }

      }
      if (object) {
        this.setData({
          goods_plugin: object,
        });
        this.setIsLove();
      }
    },
    'isRent':function(nval,oval){
      if(nval){
        let plugin = wx.getStorageSync('yz_basic_info').plugin_setting?.lease_toy.is_hide_price;
        this.setData({
          isRentSetting:plugin
        })
      }
    }
  },
  lifetimes: {
    attached(e) {
      let language = wx.getStorageSync("langIndex");
      let scribing_show = wx.getStorageSync('yz_basic_info').home.mailInfo.scribing_show && wx.getStorageSync('yz_basic_info').home.mailInfo.scribing_show == 1? 1 : 0;
      if(this.data.goodsType == 'hotelGoods'){
        let start = this.data.options.start;
        let end = this.data.options.end;
        if (new Date(this.data.options.start).getTime() < this.getCurrentTimestampToDay()) {
          start = formatTimeTwo(this.getCurrentTimestampToDay()/1000,'Y/M/D');
          const oneDayInMilliseconds = 24 * 60 * 60 * 1000;
          end = formatTimeTwo((this.getCurrentTimestampToDay()+oneDayInMilliseconds)/1000,'Y/M/D');
        }
        this.setData({
          start: start,
          end: end,
        })
        this.getDays(this.data.options.start, this.data.options.end);
      }
      this.setData({
        language: language.en,
        scribing_show,
        plugin_setting:wx.getStorageSync('yz_basic_info').plugin_setting
      });
    },
    ready() {
      if (Number(this.data.goodsInfo.market_price) == 0) {
        this.data.goodsInfo.notMarket_price = 0;
      } else {
        this.data.goodsInfo.notMarket_price = 1;
      }
      // let price_text = wx.getStorageSync("yz_basic_info").lang.goods && wx.getStorageSync("yz_basic_info").lang.goods.price ? wx.getStorageSync("yz_basic_info").lang.goods.price : "现价";
      let price_text = wx.getStorageSync("yz_basic_info").lang.goods && wx.getStorageSync("yz_basic_info").lang.goods.price ? wx.getStorageSync("yz_basic_info").lang.goods.price : "";
      let market_price_text =
        wx.getStorageSync("yz_basic_info").lang.goods && wx.getStorageSync("yz_basic_info").lang.goods.market_price ? wx.getStorageSync("yz_basic_info").lang.goods.market_price : "原价";
      const value = wx.getStorageSync("integral");

      this.setData({
        integral: value || '积分',
        getMarketPrice: market_price_text,
        getprice: price_text,
        goods_plugin: this.data.plugin,
        goodsInfo: this.data.goodsInfo
      });
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    goods_plugin: {},
    isGoodsLove: false,
    language: "",
    is_o2o: false,
    goodsInfo: [],
    // 是否开启好物圈插件
    wechatcircle_open: 0,
    wx_video_link: 0, //微信小店扩展插件
    getMarketPrice: "",
    getprice: "",
    integral: "积分",
    showmoreTitle: false,
    openVip: 2,
    available_coupon: [], //优惠券

    riseFansPopup:false, //让利涨粉弹窗
    qyPopup: false, //社群营销 二维码弹窗
    riseFansQrCode:'',
    isRentSetting:false,
    copyShow:false,
    ownerShow:true,
    profit_show:false,
    hostUrl:app.data.host,
    start:"",
    end:"",
    night_day:"",
    showEnd:false,
    showStart:false
  },

  /**
   * 组件的方法列表
   */
  methods: {
    getCurrentTimestampToDay() {
      const now = new Date();
      // 设置时间为当天的 00:00:00
      const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      // 返回时间戳，单位为毫秒
      return startOfDay.getTime();
    },
    profit_show_open(){
      this.setData({
        profit_show:true
      })
    },
    profit_show_Close(){
      this.setData({
        profit_show:false
      })
    },
    tapOwnerHide(){
      this.setData({
        ownerShow:!this.data.ownerShow
      })
    },
    init(data) {
      if (!app._isTextEmpty(data.plugin)) {
        if (data.plugin.wechatcircle_open && data.plugin.wechatcircle_open == 1) {
          this.setData({
            wechatcircle_open: 1,
          });
        }
      }

      if (data.plugin && data.plugin.wx_video_link) {
        this.setData({
          wx_video_link: data.plugin.wx_video_link,
        });
      }
    },

    getMemLevelInfo(goodsInfo){
      let lastMemLevelInfo,activeMemLevelInfo = {};
      goodsInfo.member_discount.all_level_price.forEach(element => {
        if(element.is_select) activeMemLevelInfo = element;//当前会员等级优惠信息
        if(element.is_next) lastMemLevelInfo = element;//下一个会员等级优惠信息
      });
      this.setData({
        activeMemLevelInfo,lastMemLevelInfo
      })
    },
    touchstartOn() {
      this.setData({
        copyShow:true
      });
      setTimeout(()=>{
        this.setData({
          copyShow:false
        });
      },1200);
    },
    touchCopy() {
      let that = this;
      wx.setClipboardData({
        data: this.data.goodsInfo.title,
        success(res) {
          wx.getClipboardData({
            success: function (res) {
              console.log(res);
              that.setData({
                copyShow:false
              })
              wx.showToast({
                icon: "none",
                title: '复制成功!',
                duration: 1500,
              });
            }
          })
        },
        fail(err) {
          app.tips(err.errMsg);
          that.setData({
            copyShow:false
          })
        }
      })
    },
    setTitleState(e) {
      this.setData({
        showmoreTitle: !this.data.showmoreTitle
      });
    },
    goAdvtState() {
      if (this.data.goodsInfo.has_one_goods_advertising.min_link) {
        wx.navigateTo({
          url: this.data.goodsInfo.has_one_goods_advertising.min_link
        });
      }
    },
    gotoMemberGradeList(e) {
      let tag = e.currentTarget.dataset.flag;
      if (tag == "1") {
        wx.navigateTo({
          url: "/packageB/member/MemberGradeList/MemberGradeList",
        });
      }
    },
    //是否有爱心值
    setIsLove() {
      if (this.data.goods_plugin.goods_love) {
        let love_cash = Number(this.data.goodsInfo.price) - Number(this.data.goods_plugin.goods_love.amountOfMoney);
        this.setData({
          isGoodsLove: true,
          goods_love_cash: Number(love_cash.toString().match(/^\d+(?:\.\d{0,2})?/)),
          goods_love_deduction: this.data.goods_plugin.goods_love.amountOfCoin,
          goods_love_name: this.data.goods_plugin.goods_love.name,
        });
      } else {
        this.setData({
          isGoodsLove: false,
        });
      }
    },
    gotoCoupon() {
      if (this.data.goodsType == 'hotelGoods') {
        console.log(this.data.goods_info.hotel_id);
        wx.navigateTo({
          url: "/packageC/hotel/hotelCoupon/hotelCoupon?id=" + this.data.goods_info.hotel_id,
        });
        return;
      }
      wx.navigateTo({
        url: "/packageD/coupon/coupon_store",
      });
    },
    postShow() {
      this.triggerEvent("tapPostShow");
    },
    openShare() {
      this.triggerEvent("tapOpenShare");
    },
    onFavorite() {
      this.triggerEvent("onFavorite");
    },
    // 酒店
    callhotelphone() {
      wx.makePhoneCall({
        phoneNumber: this.data.hotel_info.hotel_mobile,
      });
    },
    hotelGetData(info) {
      if (this.data.enterAt) console.log(info.get_goods, info.get_hotel_info);
      let goods_info = {
        ...info.get_goods,
        ...info.get_hotel_info.goods,
      };
      if (!this.data.enterAt) {
        wx.showModal({
          title: "提示",
          content: "选择入住酒店的时间?",
          success(data) {
            if (data.confirm) {
              if (info.get_hotel_info.goods.hotel_id) {
                wx.navigateTo({
                  url: "/packageC/hotel/HotelHome/HotelHome" + "?id=" + info.get_hotel_info.goods.hotel_id,
                });
              }
              console.log("用户点击确定");
            } else if (data.cancel) {
              console.log("用户点击取消");
            }
          },
        });
      }
      this.setData({
        goods_info: goods_info,
        hotel_info: info.get_hotel_info.hotel,
        isGoods: true,
      });
    },
    setRiseFansPop(){
      this.setData({
        riseFansPopup:!this.data.riseFansPopup
      })
    },
    //获取让利涨粉二维码
    getFriendQrCode(){
      if(this.data.riseFansQrCode!=''){
        this.setRiseFansPop();
        return;
      }
      let urlStr = app.getNetAddresss("plugin.discount-harvest-fans.frontend.controller.AddFriends.getFriendQrCode");
      app._getNetWork({
        url: urlStr,
        data:{goods_id:this.data.goodsInfo.id},
        success: (resdata) => {
          var res = resdata.data;
          if (res.result != 1) {
            return app.tips(res.msg);;
          }
          this.setData({
            riseFansPopup:true,
            riseFansQrCode:res.data.qr_code
          })

        }
      });
    },

    getQYCode(e){
      let status = e.currentTarget.dataset.status;
      this.setData({qyPopup: status})
    },
    // 酒店下单
    order() {
      let gid = this.data.prop_goods_info.get_hotel_info.goods.hotel_id;
      let end = this.data.end ;
      let start = this.data.start;
      wx.navigateTo({
        url: "/packageA/hotel/HotelGoodsOrder/HotelGoodsOrder?end=" + end + "&start=" + start + "&id=" + gid + "&goods_id=" + this.data.options.id,
      });
    },
    getDays(strDateStart, strDateEnd) {
      let strSeparator = "/"; //日期分隔符
      let oDate1, oDate2, iDays;
      oDate1 = strDateStart.split(strSeparator);
      oDate2 = strDateEnd.split(strSeparator);
      let strDateS = new Date(oDate1[0], oDate1[1] - 1, oDate1[2]);
      let strDateE = new Date(oDate2[0], oDate2[1] - 1, oDate2[2]);
      iDays = parseInt(Math.abs(strDateS - strDateE) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数
      this.setData({
        night_day: iDays
      });
    },
    showStartbtn() {
      this.setData({
        showStart: true
      })
    },
    showEndbtn() {
      this.setData({
        showEnd: true
      })
    },
    showCloseBtn() {
      this.setData({
        showStart: false,
        showEnd: false
      })
    },
    acceptTime(e) {
      let type = e.detail.type;
      let date = e.detail.date;
      if (type == "离店") {
        this.setData({
          end: date
        });
      } else if (type == "入住") {
        this.setData({
          start: date
        });
      }
      this.checkDate(type);
    },
    checkDate(type) {
      //入住日期不能为空
      //离店日期不能小于住店日期
      //离店日期不能和住店日期同一天
      let start = new Date(this.data.start).getTime();
      let end = new Date(this.data.end).getTime();
      if (app._isTextEmpty(this.data.start)) {
        wx.showToast({
          title: '请先选择入住日期',
          icon: 'none',
          duration: 2000
        });
        this.setData({
          end: ""
        });
        return;
      } else {
        if (start == end) {
          wx.showToast({
            title: '入住和离店日期不能为同一天',
            icon: 'none',
            duration: 2000
          });
          this.setData({
            end: ""
          });
          return;
        }
        if (start > end) {
          wx.showToast({
            title: '离店日期需要大于入店日期',
            icon: 'none',
            duration: 2000
          });
          this.setData({
            end: ""
          });
          return;
        }
        //关闭弹窗
        if (type == "离店") {
          //计算多少晚
          this.getDays(this.data.start, this.data.end);
          this.setData({
            showEnd: false
          });
        } else if (type == "入住") {
          this.setData({
            showStart: false
          });
        }
      }
    },
  },
});